import { FormEvent, useEffect, useState } from "react";
import { useUserStore } from "../state/users.ts";
import {
  EuiButton,
  EuiButtonEmpty,
  EuiFieldText,
  EuiForm,
  EuiFormRow,
  EuiModal,
  EuiModalBody,
  EuiModalFooter,
  EuiModalHeader,
  EuiModalHeaderTitle,
  EuiTextArea,
  EuiText,
} from "@elastic/eui";
import { updateUserAliasAndDescription } from "../commands/chats.ts";

type EditUserModalProps = {
  maybeReplyKey: string | null;
  closeModal: () => void;
  fetchUsersAndChats: () => Promise<void>;
};

export const EditUserModal = ({
  maybeReplyKey,
  closeModal,
  fetchUsersAndChats,
}: EditUserModalProps) => {
  if (!maybeReplyKey) {
    return null;
  }

  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo();

  const userAlias = userInfo[maybeReplyKey].alias;
  const userDescription = userInfo[maybeReplyKey].description;
  const userAutogeneratedName = userInfo[maybeReplyKey].displayName;

  const [draftUserAlias, setDraftUserAlias] = useState(userAlias || "");
  const [draftUserDescription, setDraftUserDescription] = useState(
    userDescription || "",
  );

  useEffect(() => {
    setDraftUserAlias(userAlias || "");
    setDraftUserDescription(userDescription || "");
  }, [userAlias, userDescription]);

  const handleEditUserChange = async () => {
    try {
      await updateUserAliasAndDescription(
        maybeReplyKey,
        draftUserAlias,
        draftUserDescription,
      );

      closeModal();

      await fetchUsersAndChats();
    } catch (e: unknown) {
      if (e instanceof Error) {
        console.error("Error handling user status change:", e.message);
      } else {
        console.error("Error handling user status change", e);
      }
    }
  };

  return (
    <EuiModal onClose={closeModal}>
      <EuiModalHeader>
        <EuiModalHeaderTitle>
          Edit source <i>{userAlias ? userAlias : userAutogeneratedName}</i>
        </EuiModalHeaderTitle>
      </EuiModalHeader>
      <EuiModalBody>
        <EuiText style={{ marginBottom: 20 }}>
          <p>This information is not visible to the source.</p>
        </EuiText>

        <EuiForm
          component="form"
          onSubmit={(e: FormEvent<HTMLFormElement>) => {
            e.preventDefault();
          }}
        >
          <EuiFormRow>
            <EuiFieldText
              placeholder="Give this source a nickname"
              name="popfirst"
              onChange={(e) => {
                setDraftUserAlias(e.target.value.substring(0, 30));
              }}
              value={draftUserAlias}
              maxLength={30}
              isInvalid={draftUserAlias.length > 30}
            />
          </EuiFormRow>
          <EuiFormRow>
            <EuiTextArea
              placeholder="Use this field to make notes about this source."
              value={draftUserDescription}
              onChange={(e) => setDraftUserDescription(e.target.value)}
            />
          </EuiFormRow>
        </EuiForm>
      </EuiModalBody>
      <EuiModalFooter>
        <EuiButtonEmpty onClick={closeModal}>Cancel</EuiButtonEmpty>
        <EuiButton
          type="submit"
          form="Submit user name and description"
          fill
          onClick={handleEditUserChange}
        >
          Save
        </EuiButton>
      </EuiModalFooter>
    </EuiModal>
  );
};
